package com.ruoyi.user.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.entity.AppUser;
import com.ruoyi.common.core.domain.model.LoginAppUser;
import com.ruoyi.common.core.domain.vo.AppUserVO;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.server.domain.ServerRegion;
import com.ruoyi.server.mapper.ServerRegionMapper;
import com.ruoyi.user.mapper.AppUserMapper;
import com.ruoyi.user.service.IAppUserService;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 用户 业务层处理
 *
 * @author ruoyi
 */
@Service
public class AppUserServiceImpl extends ServiceImpl<AppUserMapper, AppUser> implements IAppUserService {
    @Resource
    private AppUserMapper appUserMapper;
    @Resource
    private ServerRegionMapper serverRegionMapper;

    /**
     * 通过用户名查询用户
     *
     * @param userName 用户名
     * @return 用户对象信息
     */
    @Override
    public AppUser selectAppUserByUserName(String userName) {
        return appUserMapper.selectAppUserByUserName(userName);
    }

    @Override
    public AppUser selectAppUserByOpenId(String openId) {
        return appUserMapper.selectAppUserByOpenId(openId);
    }

    @Override
    public AppUser selectAppUserByUserId(Long userId) {
        return appUserMapper.selectAppUserByUserId(userId);
    }

    @Override
    public List<AppUser> selectAppUserByUserIds(List<Long> userIds) {
        return appUserMapper.selectAppUserByUserIds(userIds);
    }

    /**
     * 修改保存用户信息
     *
     * @param appUser 用户信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateAppUser(AppUser appUser) {
        return appUserMapper.updateAppUser(appUser);
    }

    /**
     * 密码校验
     *
     * @param password 明文
     * @param salt     盐
     * @param hashPwd  密文
     * @return boolean
     */
    public boolean checkPassword(String password, String salt, String hashPwd) {
        return hashPwd.equals(DigestUtils.md5DigestAsHex(password.concat(salt).getBytes()));
    }

    /**
     * 新增用户
     *
     * @param appUser
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertAppUser(AppUser appUser) {
        return appUserMapper.insertAppUser(appUser);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AppUser switchoverRegionId(AppUser appUser, Long regionId) {
        int update = appUserMapper.update(null, new UpdateWrapper<AppUser>().lambda()
                .set(AppUser::getRegionId, regionId)
                .set(AppUser::getUpdateTime, DateUtils.getNowDate())
                .set(AppUser::getUpdateBy, appUser.getUserName())
                .eq(AppUser::getUserId, appUser.getUserId())
        );
        AppUser thisAppUser = appUserMapper.selectAppUserByUserId(appUser.getUserId());
        return thisAppUser;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AppUser bindQQ(AppUser appUser, String qqCode) {
        int update = appUserMapper.update(null, new UpdateWrapper<AppUser>().lambda()
                .set(AppUser::getQqCode, qqCode)
                .set(AppUser::getUpdateTime, DateUtils.getNowDate())
                .set(AppUser::getUpdateBy, appUser.getUserName())
                .eq(AppUser::getUserId, appUser.getUserId())
        );
        AppUser thisAppUser = appUserMapper.selectAppUserByUserId(appUser.getUserId());
        return thisAppUser;
    }

    @Override
    public List<AppUserVO> selectAppUserList(AppUser appUser) {
        List<AppUser> appUserList = appUserMapper.selectAppUserList(appUser);
        List<AppUserVO> appUserVOList = BeanUtil.copyToList(appUserList, AppUserVO.class);
        if (CollectionUtils.isNotEmpty(appUserVOList)) {
            List<Long> regionIds = appUserVOList.stream().map(AppUserVO::getRegionId).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(regionIds)) {
                List<ServerRegion> serverRegionList = serverRegionMapper.selectList(new QueryWrapper<ServerRegion>().lambda()
                        .in(ServerRegion::getRegionId, regionIds)
                        .eq(ServerRegion::getDelFlag, Boolean.FALSE)
                );
                if (CollectionUtils.isNotEmpty(serverRegionList)) {
                    Map<Long, String> stringMap = serverRegionList.stream().collect(Collectors.toMap(ServerRegion::getRegionId, ServerRegion::getRegionName));
                    appUserVOList.forEach(appUserVO -> {
                        Long regionId = appUserVO.getRegionId();
                        String regionName = stringMap.get(regionId);
                        appUserVO.setRegionName(regionName);
                    });
                }
            }
        }
        return appUserVOList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateStatusByUserId(Long userId, Integer status) {
        return appUserMapper.update(null, new UpdateWrapper<AppUser>()
                .lambda()
                .set(AppUser::getStatus, status)
                .eq(AppUser::getUserId, userId)
                .eq(AppUser::getDelFlag, Boolean.FALSE)
        );
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AppUser bindPhoneNumber(LoginAppUser loginAppUser, String phoneNumber) {
        int update = appUserMapper.update(null, new UpdateWrapper<AppUser>()
                .lambda()
                .set(AppUser::getMobile, phoneNumber)
                .eq(AppUser::getUserId, loginAppUser.getAppUser().getUserId())
                .eq(AppUser::getDelFlag, Boolean.FALSE)
        );
        AppUser thisAppUser = appUserMapper.selectAppUserByUserId(loginAppUser.getAppUser().getUserId());
        return thisAppUser;
    }


    /**
     * 随即生成盐
     * 8位随机数
     *
     * @return salt 盐
     */
    private String generateSalt() {
        return RandomStringUtils.randomAlphanumeric(8);
    }

//    public static void main(String[] args) {
//        AppUserServiceImpl appUserService = new AppUserServiceImpl();
//        String password = "123456";
//        String salt = appUserService.generateSalt();
//        System.out.printf("明文密码：%s%n", password);
//        System.out.printf("盐：%s%n", salt);
//        System.out.printf("密文密码：%s%n", DigestUtils.md5DigestAsHex(password.concat(salt).getBytes()));
//    }

}
